package com.buydeem.share.rabbit.delay;

import com.buydeem.share.rabbit.Utils;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeoutException;

/**
 * 生产者
 *
 * @author zengchao
 * @date 2021-05-12 09:52:52
 */
@Slf4j
public class PluginsProductApp {

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = Utils.getFactory();
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        List<Integer> delayedTimes = Arrays.asList(5, 2, 3, 4, 1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Integer delayedTime : delayedTimes) {
            String content = String.format("消息时间:[%s],延时[%d]s", sdf.format(new Date()), delayedTime);
            log.info(content);
            byte[] msg = content.getBytes(StandardCharsets.UTF_8);
            Map<String,Object> headers = new HashMap<>();
            headers.put("x-delay",delayedTime * 1000);
            AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder().headers(headers).build();
            channel.basicPublish(Config.PLUGINS_EXCHANGE, Config.PLUGINS_ROUTING_KEY, properties, msg);
        }

        channel.close();
        connection.close();
    }
}
